import { Component, Optional, Inject } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { Router } from '@angular/router';
import { ReuseTabService } from '@delon/abc';
import { TokenService, DA_SERVICE_TOKEN } from '@delon/auth';
import { NzNotificationService, NzModalService } from 'ng-zorro-antd';
import { ApiService } from '@srvs/api.service';

@Component({
  selector: 'login',
  templateUrl: './login.component.html'
})
export class LoginComponent {

  public validateForm: FormGroup;
  public config: any = {
    loading: false
  };

  constructor(
    formBuilder: FormBuilder,
    modalSrv: NzModalService,
    private router: Router,
    private msgSrv: NzNotificationService,
    private apiSrv: ApiService,
    @Optional() @Inject(ReuseTabService) private reuseTabService: ReuseTabService,
    @Inject(DA_SERVICE_TOKEN) private tokenService: TokenService
  ) {
    this.reuseTabService.clear();
    this.validateForm = formBuilder.group({
      account: [null, [Validators.required]],
      password: [null, [Validators.required]],
      rememberMe: [true]
    });
    modalSrv.closeAll();

    if (this.tokenService.get().token) {
      const apiAuthenticate: string = '/api/account/authenticate';
      this.config.loading = true;
      this.apiSrv.get(apiAuthenticate, null, { responseType: 'text' }).subscribe(
        data => this.gotoMain(),
        error => {
          this.msgSrv.error('登录失败！', error.message);
          this.config.loading = false;
        },
        () => this.config.loading = false
      );
    }
  }

  public hasError(controlName: string, errorNames?: string[]): boolean {
    if (errorNames) {
      return (
        this.validateForm.get(controlName).dirty &&
        !!errorNames.filter(
          errorName => this.validateForm.get(controlName).hasError(errorName)
        ).length
      );
    } else {
      return !!(
        this.validateForm.get(controlName).dirty &&
        this.validateForm.get(controlName).errors
      );
    }
  }

  public submitForm(): void {
    for (const item in this.validateForm.controls) {
      this.validateForm.controls[item].markAsDirty();
      this.validateForm.controls[item].updateValueAndValidity();
    }
    if (this.validateForm.valid) {
      const apiLogin: string = '/api/account/login';
      this.config.loading = true;
      this.apiSrv.post(apiLogin, this.validateForm.value).subscribe(
        data => {
          this.reuseTabService.clear();
          this.tokenService.set({ token: data.id_token });
          this.gotoMain();
        },
        error => {
          this.msgSrv.error('登录失败！', error.message);
          this.config.loading = false;
        },
        () => this.config.loading = false
      );
    }
  }

  private gotoMain(): void {
    this.router.navigate(['./home']);
  }

}
